package repository

import (
	"RocFamilySystem/models"
	"gorm.io/gorm"
	"time"
)

type SysCacheRepository struct {
	Db *gorm.DB
}

func init() {
	registerContainer["SysCacheRepository"] = &SysCacheRepository{}
}

func (r *SysCacheRepository) SetDB(db *gorm.DB) {
	r.Db = db
}

// InsertSysCache 添加系统系统缓存
func (r *SysCacheRepository) InsertSysCache(sysCache *models.SysCache) {
	//开启事务
	db := r.Db.Begin()
	defer handleTransactional(db)
	now := models.LocalTime(time.Now())
	sysCache.CreateTime = &now
	err := db.Save(sysCache).Error
	handleRepositoryErr(err, "添加系统缓存失败")
}

// DeleteSysCache 删除系统系统缓存
func (r *SysCacheRepository) DeleteSysCache(sysCacheId int) {
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Delete(&models.SysCache{Id: &sysCacheId}).Error
	db.Where("sys_cache_id = ?", sysCacheId).Delete(models.SysCacheList{})
	handleRepositoryErr(err, "添加系统缓存失败")
}

// DeleteSysCacheBatch 批量删除系统缓存
func (r *SysCacheRepository) DeleteSysCacheBatch(ids []string) {
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Where("id in (?)", ids).Delete(models.SysCache{}).Error
	db.Where("sys_cache_id in (?)", ids).Delete(models.SysCacheList{})
	handleRepositoryErr(err, "删除系统缓存失败！")
}

// UpdateSysCache 修改系统系统缓存
func (r *SysCacheRepository) UpdateSysCache(sysCache *models.SysCache) {
	now := models.LocalTime(time.Now())
	sysCache.UpdateTime = &now
	err := r.Db.Model(sysCache).Omit("id", "create_time").Updates(sysCache).Error
	handleRepositoryErr(err, "修改系统缓存失败")
	err = r.Db.Where("sys_cache_id = ?", *sysCache.Id).Delete(models.SysCacheList{}).Error
	handleRepositoryErr(err, "修改系统缓存失败")
	r.Db.Model(sysCache).Association("SysCacheLists").Append(sysCache.SysCacheLists)
}

// SelectSysCache 查询系统系统缓存
func (r *SysCacheRepository) SelectSysCache(pageNum, pageSize int) ([]models.SysCache, int) {
	var (
		list  []models.SysCache
		total int64
	)
	db := r.Db.Model(&models.SysCache{})

	//获取总数
	db.Count(&total)

	//获取列表
	db.Offset(pageSize * pageNum).Limit(pageSize)
	db.Find(&list)

	return list, int(total)
}

// SelectSysCacheAll 查询所有系统系统缓存
func (r *SysCacheRepository) SelectSysCacheAll() []models.SysCache {
	var (
		list []models.SysCache
	)
	//获取列表
	r.Db.Preload("SysCacheLists").Find(&list)
	return list
}

// SelectSysCacheById 查询系统缓存通过ID
func (r *SysCacheRepository) SelectSysCacheById(id int) models.SysCache {
	var sysCache models.SysCache
	err := r.Db.Preload("SysCacheLists").First(&sysCache, "id = ?", id).Error
	if err != nil {
		handleRepositoryErr(err, "查询失败")
	}
	return sysCache
}
